﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Animation;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using TfsBugger.Core;
using TfsBugger.Dialogs;
using TfsBugger.Buggers;
using TfsBugger.Util.Ui;

namespace TfsBugger.Controls
{
    /// <summary>
    /// Interaction logic for CheckInBuggerTab.xaml
    /// </summary>
    public partial class CheckInBuggerUi : UserControl
    {
        public CheckInBuggerUi(CheckInBugger bugger)
        {
            InitializeComponent();
            m_checkInBugger = bugger;
            bugger.ArgsLoaded += OnBuggerArgsLoaded;
            bugger.BeginWork += OnBuggerBeginWork;
            bugger.PollingStatusUpdated += OnPollingStatusUpdated;
            bugger.TargetUpdated += OnCheckInTargetUpdated;
            bugger.WorkFinished += OnBuggerWorkFinished;
        }


        #region Fields
        private CheckInBugger m_checkInBugger;
        private ObservableCollection<object> m_changes = new ObservableCollection<object>();
	    #endregion


        #region Properties
        private Storyboard SpinnerStoryBd
        {
            get { return (Storyboard)rectSpinner.Resources["ProgressAnimation"]; }
        }


        private CheckInBugger CheckInBugger
        {
            get { return m_checkInBugger; }
        }


        private bool ClosePending { get; set; }
        #endregion


        private void OnControlLoaded(object sender, RoutedEventArgs e)
        {
            //Bind the server list 
            this.cboServers.ItemsSource = App.Servers;
            if (App.Servers.Length > 0)
                this.cboProjects.SelectedIndex = 0;

            if (CheckInBugger.HasArgs)
            {
                CheckInBuggerArgs args = (CheckInBuggerArgs)CheckInBugger.Args;
                this.cboServers.SelectedItem = args.ServerManager;
                this.cboProjects.SelectedItem = args.ProjectName;
            }

            this.lstCheckIns.ItemsSource = m_changes;
            if (CheckInBugger.IsBusy)
                OnBuggerBeginWork(null, EventArgs.Empty);
        }


        private void OnSelectedSvrChanged(object sender, SelectionChangedEventArgs e)
        {
            if (null == this.cboServers.SelectedItem)
            {
                this.cboProjects.ItemsSource = null;
                this.cboProjects.IsEnabled = false;
                return;
            }

            TfsServerManager svr = (TfsServerManager)this.cboServers.SelectedItem;
            this.cboProjects.IsEnabled = true;
            this.cboProjects.ItemsSource = from p in svr.Projects
                                           orderby p.Name ascending
                                           select p.Name;
        }


        private void OnConnectButtonClick(object sender, RoutedEventArgs e)
        {
            ServerConnectDialog connectDlg = new ServerConnectDialog();
            connectDlg.ShowDialog();

            //Update the servers dropdown 
            this.cboServers.ItemsSource = App.Servers;
        }


        private void OnSelectedProjChanged(object sender, SelectionChangedEventArgs e)
        {
            this.btnStart.IsEnabled = null != this.cboProjects.SelectedItem;
        }


        private void OnStartButtonClick(object sender, RoutedEventArgs e)
        {
            //Init the bugger and go 
            TfsServerManager svr = (TfsServerManager)this.cboServers.SelectedItem;
            CheckInBugger.SetArgs(new CheckInBuggerArgs(svr) { ProjectName = this.cboProjects.Text });
            CheckInBugger.RunAsync();
        }


        private void OnStopButtonClick(object sender, RoutedEventArgs e)
        {
            btnStop.IsEnabled = false;
            btnStart.IsEnabled = false;
            lblBugStatus.Text = "Stopping...";
            CheckInBugger.CancelAsync();
        }


        private void OnBuggerArgsLoaded(object sender, EventArgs e)
        {

        }


        private void OnBuggerBeginWork(object sender, EventArgs e)
        {
            rectSpinner.Visibility = Visibility.Visible;
            lblBugStatus.Visibility = Visibility.Visible;
            SpinnerStoryBd.Begin(this, true);

            btnStart.IsEnabled = false;
            cboProjects.IsEnabled = false;
            btnStop.IsEnabled = true;
        }


        private void OnPollingStatusUpdated(object sender, PollingStatusUpdatedEventArgs e)
        {
            lblBugStatus.Text = e.Status;
        }


        private void OnCheckInTargetUpdated(object sender, TargetUpdatedEventArgs e)
        {
            var state = (CheckInBuggerState)e.State;            
            this.m_changes.Add(new
                {
                    ChangesetDate = state.LatestChangeset.CreationDate.ToLongDateString(),
                    ChangesetName = string.Format("Changeset {0}", state.LatestChangeset.ChangesetId),
                    Committer = state.LatestChangeset.Committer,
                    Comment = state.LatestChangeset.Comment,
                    CheckinNote = string.Join(
                        ";",
                        (from n in state.LatestChangeset.CheckinNote.Values
                         select string.Format("[Name]: {0}, [Value]: {1}", n.Name, n.Value)).ToArray()),
                    ChangeCount = state.LatestChangeset.Changes.Length,
                    Changes = from c in state.LatestChangeset.Changes  
                              select c.Item.ServerItem 
                });            
        }


        private void OnBuggerWorkFinished(object sender, BuggerWorkFinishedEventArgs e)
        {
            btnStop.IsEnabled = false;
            btnStart.IsEnabled = true;
            cboProjects.IsEnabled = true;

            SpinnerStoryBd.Stop(this);
            rectSpinner.Visibility = Visibility.Hidden;
            lblBugStatus.Visibility = Visibility.Hidden;
        }

        private void OnCloseButtonClick(object sender, RoutedEventArgs e)
        {
            
        }


        private void OnDataItemPanelLoaded(object sender, RoutedEventArgs e)
        {
            DockPanel pnl = sender as DockPanel;
            if (null == pnl)
                return;

            ContentPresenter cp = pnl.TemplatedParent as ContentPresenter;
            if (null != cp)
                cp.HorizontalAlignment = HorizontalAlignment.Stretch;
        }
    }
}
